package com.wstuo.multitenancy;

import org.apache.log4j.Logger;

import java.io.InputStream;
import java.util.Properties;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.springframework.context.ApplicationContext;

import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.util.AppliactionBaseListener;
import com.wstuo.common.util.StringUtils;
/**
 * 能够解析出应用当前的 tenantId的方式 
 * @author will
 */
public class TenantIdResolver implements CurrentTenantIdentifierResolver {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TenantIdResolver.class);
	
	private static String DEFAULTTENANTID;
	private static TenantIdResolver tenantIdResolver;
	private static ThreadLocal<String> threadLocalTenantId = new ThreadLocal<String>();

	public String resolveCurrentTenantIdentifier() {
		//System.out.println(new Date()+"本次操作的TenantId："+getTenantId());
		return getTenantId();
	}
	public boolean validateExistingCurrentSessions() {
		return false;
	}
	
	/**
	 * get tenant identifier
	 * @return tenant identifier
	 * @author WSTUO
	 */
	public synchronized String getTenantId(){
		String tenantId =null;
		ApplicationContext ctx =AppliactionBaseListener.ctx;
		if(ctx!=null){
			//Session
			AppContext appctx = (AppContext)ctx.getBean("appctx");
			if(appctx!=null){
				tenantId = appctx.getCurrentTenantIdNotDefaultValue();
			}
			if(!StringUtils.hasText(tenantId)){
				String localTenantId = threadLocalTenantId.get();
				if(StringUtils.hasText(localTenantId)){
					tenantId = localTenantId;
				}
			}
		}
		if(!StringUtils.hasText(tenantId)){
			tenantId = getDefaultTenantId();
		}
		return tenantId;
	}
	
	/**
	 * set tenant identifier
	 * @author WSTUO
	 */
	public synchronized void setTenantId(String tenantId){
		threadLocalTenantId.set(tenantId);
	}
	
	
	public static TenantIdResolver getInstance(){
		if(tenantIdResolver==null){
			tenantIdResolver = new TenantIdResolver();
		}
		return tenantIdResolver;
	}
	
	public String getDefaultTenantId(){
		if(DEFAULTTENANTID==null){
			Properties prop = new Properties();
			try {
				InputStream in = getClass().getResourceAsStream("/hibernate.properties");
				prop.load(in);
				DEFAULTTENANTID = prop.getProperty("dataSource.databaseName");
			} catch (Exception e) {
				logger.error(e);
			}
			
		}
		return DEFAULTTENANTID;
	}
	
	
}
